#pragma once

#include <iostream>
#include <string>
#include <functional>
#include <pthread.h>

using task_t = std::function<void()>;
class Thread
{
private:
    static void *Handler(void *args)
    {
        auto self = static_cast<Thread *>(args);
        self->_task();
        return nullptr;
    }
public:
    Thread(const Thread&) = delete;
    Thread& operator==(const Thread&) = delete;
    Thread(const task_t task) : _task(task),_isrunning(true)
    {
        int ret = ::pthread_create(&_thread, nullptr, Handler, this);
        if (ret != 0)
        {
            std::cerr << "线程创建失败!" << std::endl;
        }
    }
    ~Thread()
    {
        if(_isrunning) Join();
    }
    bool Join()
    {
        if (::pthread_join(_thread, nullptr) != 0)
        {
            std::cerr << "线程等待失败!" << std::endl;
            return false;
        }
        _isrunning = false;
        return true;
    }
    void Detach()
    {
        if (::pthread_detach(_thread) != 0)
        {
            std::cerr << "线程分离失败!" << std::endl;
        }
    }
    pthread_t Id()
    {
        return ::pthread_self();
    }
private:
    pthread_t _thread;
    task_t _task;
    bool _isrunning = false;
};